import axios from 'axios'
import store from '../store'
import { Loading } from 'element-ui'

let baseRequest = {
  baseURL: 'http://localhost:8081',
  timeout: 3000
}

export default {
  request (requestConfig, isShowDialog) {
    return new Promise((resolve, reject) => {
      let loadingIns = Loading.service({ fullscreen: true })
      axios.request(requestConfig).then((response) => {
        resolve(response.data)
      }).catch((error) => {
        if (error.request.readyState === 4) {
          let errorStr = error + ''
          // 超时处理
          if (errorStr.indexOf('timeout') > -1) {
            store.dispatch('showDialog', 'API 请求超时')
          } else {
            // 正常错误处理
            if (isShowDialog) {
              store.dispatch('showDialog', error.response.data.Error)
            }
            reject(error.response.data)
          }
        }
      }).finally(() => {
        loadingIns.close()
      })
    })
  },
  get (url, isShowDialog = true) {
    let request = baseRequest
    request.url = url
    request.method = 'GET'

    return this.request(request, isShowDialog)
  },
  post (url, data, isShowDialog = true) {
    let request = baseRequest
    request.url = url
    request.method = 'POST'
    request.data = data

    return this.request(request, isShowDialog)
  },
  put (url, data, isShowDialog = true) {
    let request = baseRequest
    request.url = url
    request.method = 'PUT'
    request.data = data

    return this.request(request, isShowDialog)
  },
  delete (url, data, isShowDialog = true) {
    let request = baseRequest
    request.url = url
    request.method = 'DELETE'
    request.data = data

    return this.request(request, isShowDialog)
  },
  setBaseUrl (baseUrl) {
    baseRequest.baseURL = baseUrl
  }
}
